<?php
namespace App\Middlewares;

use Core\Middleware;
use Core\Request;

class CorsMiddleware extends Middleware {
    protected $config;
    
    public function __construct() {
        // 获取配置
        $this->config = require __DIR__ . '/../../config/app.php';
    }
    
    public function handle(Request $request, \Closure $next) {
        $corsConfig = $this->config['cors'] ?? [];
        
        // 处理预检请求
        if ($request->getMethod() === 'OPTIONS') {
            header('Access-Control-Allow-Origin: ' . implode(', ', $corsConfig['allowed_origins'] ?? ['*']));
            header('Access-Control-Allow-Methods: ' . implode(', ', $corsConfig['allowed_methods'] ?? ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']));
            header('Access-Control-Allow-Headers: ' . implode(', ', $corsConfig['allowed_headers'] ?? ['Content-Type', 'Authorization', 'X-Requested-With']));
            header('Access-Control-Max-Age: ' . ($corsConfig['max_age'] ?? 0));
            
            if ($corsConfig['supports_credentials'] ?? false) {
                header('Access-Control-Allow-Credentials: true');
            }
            
            exit(0);
        }
        
        // 添加CORS头
        header('Access-Control-Allow-Origin: ' . implode(', ', $corsConfig['allowed_origins'] ?? ['*']));
        header('Access-Control-Allow-Methods: ' . implode(', ', $corsConfig['allowed_methods'] ?? ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']));
        header('Access-Control-Allow-Headers: ' . implode(', ', $corsConfig['allowed_headers'] ?? ['Content-Type', 'Authorization', 'X-Requested-With']));
        
        if (!empty($corsConfig['exposed_headers'])) {
            header('Access-Control-Expose-Headers: ' . implode(', ', $corsConfig['exposed_headers']));
        }
        
        if ($corsConfig['supports_credentials'] ?? false) {
            header('Access-Control-Allow-Credentials: true');
        }
        
        return $next($request);
    }
}